import React, { PureComponent } from 'react'
import {
  message, Button, Alert, Popconfirm, Modal, Form, Input, Select,
} from 'antd'
import { connect } from '@umijs/max'
import {
 ProTable, ProTableOperate, ProTableOptions, InputSearch,
} from '@/components'
import { getRoleList, getUserNamePageList } from './api'
import Https from '@/utils/https'
import styles from './index.less'

const { OperateItem } = ProTableOperate

@connect(({ global }) => ({ ...global }))
class SecretKey extends PureComponent {
  constructor(props) {
    super(props)
    this.state = {
      show: false,
      roleList: [],
      userList: [],
      editId: null,
      query: {},
    }
    this.form = React.createRef()
  }

  componentDidMount() {
    getRoleList().then(
      (res) => {
        if (res?.result?.length > 0) {
          // 空间内不能添加超级管理员和空间所有者角色，需要过滤
          const filterRoleList = res.result.filter(role => role.roleName !== '超级管理员' && role.roleName !== '空间所有者')
          this.setState({roleList: filterRoleList})
        }
      },
    )
    getUserNamePageList().then(
      (res) => {
        if (res?.length > 0) {
          this.setState({ userList: res })
        }
      },
    )
  }

  handleAddMember = () => {
    this.form.current.validateFields().then(values => {
      const { editId } = this.state
      if (editId) {
        Https.post(`/api/v1/management/user/project/updateProjectUser?roleId=${values.roleId}&userName=${values.userName}`).then(
          (res) => {
            if (res) {
              message.success('编辑成功')
              this.setState({ show: false, editId: null, query: {} })
            }
          },
        )
      } else {
        Https.post(`/api/v1/management/user/project/addProjectUser?roleId=${values.roleId}&userName=${values.userName}`).then(
          (res) => {
            if (res) {
              message.success('添加成功')
              this.setState({ show: false, query: {} })
            }
          },
        )
      }
    })
  }

  deleteUser = (userName) => {
    Https.post(`/api/v1/management/user/project/deleteProjectUser?userName=${userName}`).then(
      (res) => {
        if (res) {
          message.success('删除成功')
          this.setState({ query: {}, visibleDele: false })
        }
      },
    )
  }

  render() {
    const {
      show, roleList, query, editId, userList,
    } = this.state
    return (
      <div className={styles.secret_key_page}>
        <div className={styles.secret_key_title}>空间成员</div>
        <ProTableOperate
          toggleOperate={false} // 是否隐藏 收起/展开 按钮 (如果隐藏按钮，handleToggleSta设置属性值不生效)
          unfolded
        >
          <OperateItem align="left">
            <InputSearch
              placeholder="请输入成员账号或姓名"
              value={this.state.dsName}
              onChange={(e) => {}}
              onSearch={() => {}}
            />
          </OperateItem>
          <OperateItem itemType="btn">
            {
                [
                  <Button
                    type="primary"
                    onClick={() => {
                      this.setState({ show: true })
                    }}
                    key="new"
                  >
                    添加成员
                  </Button>,
                ]
              }
          </OperateItem>
        </ProTableOperate>
        <ProTable
          url="/api/v1/management/user/project/getProjectUser"
          query={query}
          columns={[
            {
              title: '账号',
              dataIndex: 'userName',
              width: '10%',
              key: 'userName',
            },
            {
              title: '邮箱',
              dataIndex: 'email',
              width: '10%',
              key: 'email',
            },
            {
              title: '姓名',
              dataIndex: 'displayName',
              width: '20%',
              key: 'displayName',
            },
            {
              title: '手机号',
              dataIndex: 'phoneNumber',
              width: '20%',
              key: 'phoneNumber',
            },
            {
              title: '角色',
              dataIndex: 'roleName',
              width: '20%',
              key: 'roleName',
            },
            {
              title: '加入时间',
              dataIndex: 'created',
              width: '10%',
              key: 'created',
            },
            {
              title: '操作',
              dataIndex: 'operation',
              width: '15%',
              key: 'operation',
              render: (text, record) => (
                <ProTableOptions>
                  {
                    !record.isSystem ? (
                      <span
                        key="edit"
                        onClick={() => {
                          this.setState({ show: true, editId: record.id }, () => {
                            this.form.current.setFieldsValue({
                              userName: record.userName,
                              roleId: record.roleId,
                            })
                          })
                        }}
                      >
                        编辑
                      </span>
                    ) : null
                  }
                  {
                    !record.isSystem ? (
                      <Popconfirm
                        title="确定要删除吗？"
                        onConfirm={() => { this.deleteUser(record.userName) }}
                        visible={this.state.visibleDele === record.id}
                        onCancel={() => { this.setState({ visibleDele: false }) }}
                        okText="是"
                        cancelText="否"
                        key="del"
                      >
                        <span onClick={() => { this.setState({ visibleDele: record.id }) }}>
                          删除
                        </span>
                      </Popconfirm>
                    ) : null
                  }
                </ProTableOptions>
              ),
            },
          ]}
        />
        <Modal title={editId ? '编辑成员' : '添加成员'} visible={show} onCancel={() => { this.setState({ show: false, editId: null }); this.form.current.resetFields() }} onOk={this.handleAddMember}>
          <Form
            ref={this.form}
          >
            <Form.Item label="账号" name="userName" rules={[{ required: true, message: '请选择账号' }]}>
              <Select placeholder="请选择账号" disabled={editId}>
                {
                  userList.map((item) => (
                    <Select.Option key={item} value={item}>
                      {item}
                    </Select.Option>
                  ))
                }
              </Select>
            </Form.Item>
            <Form.Item label="角色" name="roleId" rules={[{ required: true, message: '请选择角色' }]}>
              <Select placeholder="请选择角色">
                {
                  roleList.map((item) => (
                    <Select.Option key={item.id} value={item.id}>
                      {item.roleName}
                    </Select.Option>
                  ))
                }
              </Select>
            </Form.Item>
          </Form>
        </Modal>
      </div>
    )
  }
}

export default SecretKey
